package com.hanson.common.Interceptor;

import com.alibaba.fastjson.JSON;
import com.hanson.common.bean.ResultMessage;
import com.hanson.common.service.RedisService;
import com.hanson.common.util.BusinessUtil;
import com.hanson.entity.UserBean;
import com.hanson.service.UserService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.util.http.URIUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    private static final String[] IGNORE_URI = {"/js/", ".js", ".css", ".jpg", ".ttf", ".woff",
            "woff2", ".txt", ".gif", ".png", "/error", ".PNG", ".GIF", ".JPG", ".xls", ".xlsx", ".swf", "favicon.ico",
            "/admin/login", "/weixin",
            "/api/user/getOpenIdByCode/",
            "/api/index/getSlides",
            "/api/index/getNavs",
            "/api/index/getHotGoods/",
            "/api/index/getBenefitGoods/",
            "/api/index/getBestGoods/",
            "/api/index/getRecommendGoods",
            "/api/index/getRecommendSearch",
            "/api/index/search",
            "/api/index/searchType/",
            "/api/goodsType/getRootGoodsType/",
            "/api/goodsType/getChildGoodsType/",
            "/api/goods/goodsDetail/",
            "/api/weixin/notify/",
            "/api/groupGoods/select/",
            "/api/groupGoods/groupDetail/",
            "/api/skillGoods/query",
            "/api/skillGoods/skillDetail/",
            "/api/index/getSurplusSecond",
            "/api/index/getSkillGoods",
            "/api/index/getGroupGoods",
            "/api/index/getCoupons",
            "/api/goods/getShareParam"
    };

    @Autowired
    private RedisService redisService;
    @Autowired
    private UserService userService;

    /**
     * 预处理回调方法，实现处理器的预处理
     * 返回值：true表示继续流程；false表示流程中断，不会继续调用其他的拦截器或处理器
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String requestUri = request.getRequestURI();
        String openId = BusinessUtil.getHeaderOpenId(request);
        String client = BusinessUtil.getHeaderClient(request);
        log.info("访问URL:{} openId:{} client:{}", requestUri, openId, client);
        for (String s : IGNORE_URI) {
            if (requestUri.contains(s)) {
                return true;
            }
        }
        if (requestUri.contains("/api/")) {
            if (StringUtils.isEmpty(openId)) {
                response.setCharacterEncoding("utf-8");
                response.setContentType("application/json; charset=utf-8");
                PrintWriter writer = response.getWriter();
                writer.write(JSON.toJSONString(ResultMessage.error(HttpStatus.FORBIDDEN.value(), "无权限访问当前资源,请登录！")));
                return false;
            } else {
                int result = userService.countByOpenId(openId);
                //当前用户不存在了
                if (result == 0) {
                    response.setCharacterEncoding("utf-8");
                    response.setContentType("application/json; charset=utf-8");
                    PrintWriter writer = response.getWriter();
                    writer.write(JSON.toJSONString(ResultMessage.error(HttpStatus.FORBIDDEN.value(), "无权限访问当前资源,请登录！")));
                    return false;
                }
            }
            return true;
        } else {
            boolean checkCookies = false;
            String token = BusinessUtil.getCookieToken(request, "token");
            if (StringUtils.isNotEmpty(token)) {
                UserBean userBean = (UserBean) redisService.get("LOGIN:" + token);
                if (userBean != null && null != userBean.getId()) {
                    checkCookies = true;
                }
            }
            if (!checkCookies) {
                response.sendRedirect(request.getContextPath() + "/admin/login");
                return false;
            } else {
                //刷新
                Cookie userCookie = new Cookie("token", token);
                //存活期60分钟
                userCookie.setMaxAge(60 * 60 * 24);
                userCookie.setPath("/");
                response.addCookie(userCookie);

                redisService.expire("LOGIN:" + token, 60 * 60L);
                return true;
            }
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {

    }

}